<template>
  <section>
    <div>
      <search-bar more-display>
      <el-form ref="searchForm" label-position="right" :model="searchForm" class="f-bc"
               label-width="120px">
        <el-row  :span="24">
          <el-col :span="8">
            <el-form-item  label="运价文价名称" prop="fileName">
              <el-input v-model="searchForm.fileName"
                        placeholder="请输入文价名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="运价类型" prop="freightType">
              <el-select v-model="searchForm.freightType"
                         filterable placeholder="请选择运价类型">
                <el-option
                  v-for="orderSource in $store.getters.TARIFF_CLASSIFICATION"
                  :label="orderSource.cnDictValname"
                  :key="orderSource.dictVal"
                  :value="orderSource.dictVal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="发布渠道" prop="stowageId">
              <el-select v-model="searchForm.stowageId"
                         filterable
                         remote
                         :remote-method="getStowagesCores"
                         placeholder="请选择发布渠道">
                <el-option v-for="stowagesCore in stowagesCores"
                           :label="stowagesCore.name"
                           :key="stowagesCore.id"
                           :value="stowagesCore.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-col :span="8">
            <el-form-item  label="发布状态" prop="status">
              <el-select v-model="searchForm.status"
                         filterable placeholder="请选择发布状态">
                <el-option style="width: 100%"
                           v-for="orderSource in $store.getters.TARIFF_RELEASE_STATUS"
                           :label="orderSource.cnDictValname"
                           :key="orderSource.dictVal"
                           :value="orderSource.dictVal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="生效日期" prop="operativeDate">
              <el-date-picker
                              v-model="searchForm.operativeDate"
                              type="daterange"
                              placeholder="选择日期范围">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="失效日期" prop="loseEfficacyDate">
              <el-date-picker
                              v-model="searchForm.loseEfficacyDate"
                              type="daterange"
                              placeholder="选择日期范围">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-col :span="8">
            <el-form-item  label="标准运价名称" prop="standardPriceName">
              <el-input v-model="searchForm.standardPriceName"  placeholder="请输入标准运价名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="标准运价编号" prop="standardPriceNumber">
              <el-input v-model="searchForm.standardPriceNumber"  placeholder="请输入标准运价编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="创建日期" prop="createDate">
              <el-date-picker
                              v-model="searchForm.createDate"
                              type="daterange"
                              placeholder="选择日期范围">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      </search-bar>
      <div class="f-mt f-wa">
        <el-button type="primary" class="f-wa f-fr f-ml10 f-mr20 f-mb10"
                   @click="resetSearchForm('searchForm')">重置
        </el-button>
        <el-button type="primary" class="f-wa f-fr f-ml10 " @click="searchOrders">查询</el-button>
      </div>
    </div>
    <el-table @selection-change="selsChange" @sort-change="sortChange" :data="freightTableData" highlight-current-row
              border max-height="660">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="statusName" label="发布状态" width="120">
      </el-table-column>
      <el-table-column prop="standardPriceNumber" label="标准运价编号" width="140">
      </el-table-column>
      <el-table-column prop="standardPriceName" label="标准运价名称" width="140">
      </el-table-column>
      <el-table-column prop="freightTypeName" label="运价类型" width="120">
      </el-table-column>
      <el-table-column prop="fileNumber" label="运价文件编号" width="160">
      </el-table-column>
      <el-table-column prop="fileName" label="运价文件名称" width="150">
      </el-table-column>
      <el-table-column prop="createUserName" label="创建人" width="120">
      </el-table-column>
      <el-table-column prop="createDate" label="创建日期" width="160">
      </el-table-column>
      <el-table-column prop="stowageName" label="发布渠道" width="160">
      </el-table-column>
      <el-table-column prop="operativeDate" label="生效时间" width="160">
      </el-table-column>
      <el-table-column prop="loseEfficacyDate" label="失效时间" width="160">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300">
        <template slot-scope="scope">
          <!--待提交-->
          <el-button  type="primary" class="f-mt10 f-mb10 f-ml5"
                     v-if="scope.row.status===112001001"
                     @click="changeStatus(scope.row.id, 112001002,'提交审核')">提交审核
          </el-button>
          <el-button  type="primary" class="f-ml5" v-if="scope.row.status===112001001"
                     @click="freightDetailPage(scope.row.id)">维护运价
          </el-button>
          <el-button  type="danger" class="f-mb10 f-ml5" v-if="scope.row.status===112001001"
                     @click="deleteFreight(scope.row.id)">删除
          </el-button>
          <!--待审核-->
          <el-button  type="primary" class="f-ml5" v-if="scope.row.status===112001002"
                     @click="freightDetailPage(scope.row.id)">明细
          </el-button>
          <el-button  type="primary" class="f-ml5" v-if="scope.row.status===112001002"
                     @click="changeStatus(scope.row.id, 112001006,'发布')">发布
          </el-button>
          <el-button  type="warning" class="f-ml5" v-if="scope.row.status===112001002"
                     @click="changeStatus(scope.row.id, 112001001,'撤销')">撤销审核
          </el-button>
          <!--已发布 | 已过期 | 已禁用-->
          <el-button  type="primary" class="f-ml5"
                     v-if="scope.row.status===112001003||scope.row.status===112001005||scope.row.status===112001006"
                     @click="freightDetailPage(scope.row.id)">明细
          </el-button>
          <!--<el-button  type="warning" class="f-ml5"-->
                     <!--v-if="scope.row.status===112001003"-->
                     <!--@click="changeStatus(scope.row.id, 112001002,'撤销')">撤销发布-->
          <!--</el-button>-->
          <!--已启用-->
          <el-button  type="primary" v-if="scope.row.status===112001004" class="f-ml5"
                     @click="freightDetailPage(scope.row.id)">明细
          </el-button>

          <el-button  type="warning" v-if="btns.indexOf('disable_btn')>-1 && scope.row.status===112001004" class="f-ml5"
                     @click="changeStatus(scope.row.id, 112001006,'禁用')">禁用
          </el-button>

          <el-button  type="success" v-if="btns.indexOf('enable_btn')>-1 && scope.row.status===112001006" class="f-ml5"
                     @click="changeStatus(scope.row.id, 112001004,'启用')">启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>

    <el-dialog title="新增运价文件" :visible.sync="freightFormDialog" size="tiny">
      <el-form label-width="100px" ref="freightForm" :model="freightForm" :rules="freightFormRules">
        <el-form-item label="运价名称" prop="fileName">
          <el-input v-model="freightForm.fileName" class="f-w50" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="运价类型" prop="freightType">
          <el-select v-model="freightForm.freightType" class="f-w50"
                     filterable placeholder="请选择运价类型">
            <el-option style="width: 200px"
                       v-for="orderSource in $store.getters.TARIFF_CLASSIFICATION"
                       :label="orderSource.cnDictValname"
                       :key="orderSource.dictVal"
                       :value="orderSource.dictVal"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布渠道" prop="stowageId">
          <el-select v-model="freightForm.stowageId"
                     class="f-w50"
                     filterable
                     remote
                     :remote-method="getStowagesCores"
                     placeholder="请选择发布渠道">
            <el-option v-for="stowagesCore in stowagesCores"
                       :label="stowagesCore.name"
                       :key="stowagesCore.id"
                       :value="stowagesCore.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-for="(domain, index) in freightForm.destinationOrganizationIds" :key="index" label="目的地组织"
                      :rules="{required: true, type: 'array', message: '请选择目的地组织', trigger: 'change'}"
                      :prop="'destinationOrganizationIds.' + index + '.value'">
          <el-cascader
            placeholder="请目的地组织"
            class="f-w50"
            :options="$store.state.initOrganizations"
            :props="{label: 'name',value: 'id'}"
            change-on-select
            v-model="domain.value"></el-cascader>
          <el-button type="primary" icon="el-icon-minus" v-if="index !== freightForm.destinationOrganizationIds.length-1" @click="removeDestinationOrganization(index)"></el-button>
          <el-button type="primary" icon="el-icon-plus" v-if="index === freightForm.destinationOrganizationIds.length-1" @click="addDestinationOrganization"></el-button>
        </el-form-item>
        <el-form-item label="生效时间" prop="operativeDate">
          <el-date-picker
            class="f-w50"
            v-model="freightForm.operativeDate"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效时间" prop="loseEfficacyDate">
          <el-date-picker
            class="f-w50"
            v-model="freightForm.loseEfficacyDate"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label=" 备 注 ">
          <el-input type="textarea" v-model="freightForm.remark" class="f-w50" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="freightFormDialog = false">取 消</el-button>
        <el-button type="primary" @click="createFreightForm">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
/* eslint-disable no-extend-native */
import {getFreights, createFreight, deleteFreight, changeStatus} from '../../api/freight/freightApi.js';
import {
  searchStowageCore
} from '../../api/system/stowageCore';
import {isEmpty, resetObjNull} from '../../lib/util.js';

export default {
  data () {
    return {
      token: this.$store.state.token,
      freightFormDialog: false, // 新增运价文件dialog
      stowagesCores: [],
      /**
         * 运价页面检索model
         */
      searchForm: {
        fileName: null,
        freightType: null,
        status: null,
        stowageId: null,
        operativeDate: null,
        loseEfficacyDate: null,
        standardPriceNumber: null,
        standardPriceName: null,
        createDate: null
      },

      freightForm: {
        fileName: '',
        freightType: '',
        stowageId: '',
        destinationOrganizationIds: [
          {value: []}
        ],
        destinationOrganizationId: '',
        destinationOrganizationName: '',
        operativeDate: null,
        operativeDateTemp: null,
        loseEfficacyDate: null,
        loseEfficacyDateTemp: null,
        remark: ''
      },
      /**
         * 新增运价文件正则验证
         */
      freightFormRules: {
        fileName: [
          {required: true, message: '请输入运价文件名称', trigger: 'blur'}
        ],
        freightType: [
          {required: true, type: 'number', message: '请选择运价文件类型', trigger: 'change'}
        ],
        stowageId: [
          {required: true, message: '请选择发布渠道', trigger: 'change'}
        ],
        operativeDate: [
          {required: true, type: 'date', message: '请选择生效时间', trigger: 'blur'}
        ],
        loseEfficacyDate: [
          {required: true, type: 'date', message: '请选择失效时间', trigger: 'blur'}
        ]
      },

      // 验证规则

      use_issueVal: '',
      sels: [],
      freightTableData: [],

      total: 0,
      currentPage: 1,
      pageSize: 10,

      sortProp: null,
      sortOrder: 'ascending'
    };
  },
  methods: {
    removeDestinationOrganization (index) {
      this.freightForm.destinationOrganizationIds.splice(index, 1);
    },
    addDestinationOrganization () {
      this.freightForm.destinationOrganizationIds.push({value: []});
    },
    freightFormDialogClick () {
      this.resetForm();
      this.freightFormDialog = true;
    },

    modifFreightFileDialog (row) {
      this.freightFormDialog = true;
      this.resetForm();
      this.freightForm = Object.assign({
        fileName: '',
        freightType: '',
        stowageId: '',
        destinationOrganizationId: '',
        destinationOrganizationIds: [],
        destinationOrganizationName: '',
        operativeDate: null,
        loseEfficacyDate: null,
        remark: ''
      }, row);
      this.freightForm.operativeDate = new Date(row.operativeDate);
      this.freightForm.loseEfficacyDate = new Date(row.loseEfficacyDate);
      this.freightForm.destinationOrganizationIds = this.freightForm.destinationOrganizationId.split(';').map(o => {
        return {value: o.split(',')};
      });
    },

    getStowagesCores (val) {
      let filters = isEmpty(val) ? '' : 'LIKE_name=' + val;
      searchStowageCore({
        filters: filters,
        sorts: '',
        size: '15',
        page: '1'
      }).then((res) => {
        this.stowagesCores = res.data.detailModelList;
      });
    },

    /**
       * 跳转到运价明细页面
       */
    freightDetailPage (id) {
      this.$router.push('/freight_manage/freightDetail/' + id);
    },

    /**
       * 新增运价文件
       * 1，表单验证
       */
    createFreightForm () {
      this.$refs['freightForm'].validate((valid) => {
        if (valid) {
          if (this.freightForm.operativeDate > this.freightForm.loseEfficacyDate) {
            this.$message.error('生效时间不能超过失效时间！');
            return;
          }
          let o = Object.assign({}, this.freightForm);
          o.destinationOrganizationId = this.freightForm.destinationOrganizationIds.map(o => {
            return o.value.join(',');
          }).join(';');
          o.operativeDate = o.operativeDate.toJSON();
          o.loseEfficacyDate = o.loseEfficacyDate.toJSON();
          createFreight(this.token, o).then((res) => {
            if (res.data.successFlg) {
              this.freightFormDialog = false;
              this.$message.success('新增成功');
              this.getTableData();
            }
          }).catch(function (error) {
            this.$message.error('新增失败');
            console.log(error);
          });
        }
      });
    },
    /**
       * 删除运价文件
       */
    deleteFreight (freightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFreight(freightId).then((res) => {
          if (res.data.successFlg) {
            this.$message.success('删除成功');
            this.getTableData();
          } else {
            this.$message.error(res.data.errorMsg);
          }
        }).catch(function (error) {
          this.$message.error('删除失败');
          console.log(error);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    /**
       * 根据运价文件id,更改运价文件状态
       */
    changeStatus (id, status, msg) {
      this.$confirm('更改运价文件状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeStatus(id, status).then((res) => {
          if (res.data.successFlg) {
            this.$message.success(msg + '成功');
            this.getTableData();
          }
        }).catch(function (error) {
          this.$message.error(msg + '失败');
          console.log(error);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' + msg
        });
      });
    },

    // 跳转领用记录
    receive (index, row) {
      this.$router.push('/marketing/receive/', row.id);
    },
    // 跳转到新增页面
    //            freightAdd(){
    //                this.$router.push('/freight_manage/freightAdd');
    //            },

    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchOrders();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchOrders();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchOrders();
    },

    /**
       * 多条件检索订单信息
       */
    searchOrders () {
      this.fs = '';
      let sf = this.searchForm;
      let filters = '';
      for (let s in sf) {
        if (isEmpty(sf[s])) {
          continue;
        }

        if (s === 'operativeDate') {
          //            let startDate = (sf[s][0]).Format('yyyy-MM-dd');
          //            let endDate = (sf[s][1]).Format('yyyy-MM-dd');
          let startDate = (sf[s][0]).Format('yyyy-MM-dd');
          let endDate = (this.$ue.addDays(sf[s][1], 1)).Format('yyyy-MM-dd');
          filters += s + '>=' + startDate + ';' + s + '<=' + endDate + ';';
          continue;
        }
        if (s === 'loseEfficacyDate') {
          //            let startDate = (sf[s][0]).Format('yyyy-MM-dd');
          //            let endDate = (sf[s][1]).Format('yyyy-MM-dd');
          let startDate = (sf[s][0]).Format('yyyy-MM-dd');
          let endDate = (this.$ue.addDays(sf[s][1], 1)).Format('yyyy-MM-dd');
          filters += s + '>=' + startDate + ';' + s + '<=' + endDate + ';';
          continue;
        }

        if (s === 'createDate') {
          //            let startDate = (sf[s][0]).Format('yyyy-MM-dd');
          //            let endDate = (sf[s][1]).Format('yyyy-MM-dd');
          let startDate = (sf[s][0]).Format('yyyy-MM-dd');
          let endDate = (this.$ue.addDays(sf[s][1], 1)).Format('yyyy-MM-dd');
          filters += s + '>=' + startDate + ';' + s + '<=' + endDate + ';';
          continue;
        }

        if (s === 'freightType' || s === 'status' || s === 'stowageId') {
          filters += s + '=' + sf[s] + ';';
          continue;
        }

        filters += s + '?' + sf[s] + ';';
      }
      if (filters.substring(filters.length - 1, filters.length) === ';') {
        filters = filters.substring(0, filters.length - 1);
      }

      this.getTableData(filters);
    },

    // 重置查询条件
    resetSearchForm (formName) {
      resetObjNull(this.searchForm);
      //        this.$refs[formName].resetFields();
    },

    // 重置表单
    resetForm () {
      if (this.$refs.freightForm) {
        this.$refs.freightForm.resetFields();
      }
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      for (let p in this.freightForm) {
        if (this.freightForm[p] instanceof Array) {
          this.freightForm[p] = [];
        } else {
          this.freightForm[p] = null;
        }
      }
      this.freightForm.destinationOrganizationIds = [{value: []}];
    },
    // 获取表格数据
    getTableData (filters) {
      getFreights({
        page: this.currentPage,
        size: this.pageSize,
        filters: filters,
        sorts: '-createDate'
      }).then((res) => {
        if (res.data.successFlg) {
          this.freightTableData = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
        }
      });
    }
  },
  computed: {
    btns () {
      return this.$store.state.btns[this.$route.path] || [];
    },
    querys () {
      return this.$store.state.querys[this.$route.path + '#default'] || [];
    }
  },
  // 初始化数据
  mounted () {
    this.getTableData();
    this.getStowagesCores();
    this.$store.commit('initDict');
    this.$store.commit('initOrganizations');
  }
};
</script>

<style lang="less" scoped>
  .f-w70 {
    width: 70% !important;
  }

  .f-ml5 {
    margin-left: 5px !important;
  }

  .f-w50 {
    width: 50% !important;
  }

  .active {
    display: none
  }
</style>
